<template>
  <form >
    <label for="">书名：</label>
    <input type="text" v-model="book.bookName"><br>
    <label for="">作者：</label>
    <input type="text" v-model="book.author"><br>

    <input type="button" value="保存" @click="btnSave">
    <input type="button" value="取消" @click="btnCancel">
  </form>
</template>

<script setup>
import { getById, postItem, putItem } from '@/api/bookapi';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter()
const route = useRoute()
const book = ref({
  bookName:'',
  author:''
})

onMounted(async ()=>{
  const id = route.params.id
  if (id) {
    const data = await getById(id)
    console.log(data);
    
    book.value = data.data
  }
})



async function btnSave(){
  console.log('保存');
  const id =route.params.id || 0
  let data;
  if (id === 0) {
    data = await postItem(book.value)
    console.log(data.data);
  }else{
    data = await putItem(id,book.value)

  }  
  router.push('/book')
}

function btnCancel(){
  router.push('/book')
}

</script>



